from rest_framework import serializers
from ..models.dimensionModel import *


class DimensionListQuerySerializer(serializers.Serializer):
    dimension_name = serializers.CharField(required=False, allow_blank=True)
    sei_id = serializers.CharField(required=False, allow_blank=True)
    basic_dimension_composition = serializers.JSONField(required=False)
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False, allow_blank=True)
    sort_order = serializers.CharField(required=False, allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "dimension_name" in attrs:
            attrs["dimension_name"] = attrs["dimension_name"].strip()
            if attrs["dimension_name"] == "":
                attrs.pop("dimension_name")
        if "sei_id" in attrs:
            attrs["sei_id"] = attrs["sei_id"].strip()
            if attrs["sei_id"] == "":
                attrs.pop("sei_id")
        if "basic_dimension_composition" in attrs:
            if len(attrs["basic_dimension_composition"]) == 0:
                attrs.pop("basic_dimension_composition")
            else:
                attrs["basic_dimension_composition"] = attrs["basic_dimension_composition"]
        if ("dimension_name" not in attrs or attrs["dimension_name"] == "") and ("sei_id" not in attrs or attrs["sei_id"] == "") and ("basic_dimension_composition" not in attrs or attrs["basic_dimension_composition"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs

    @classmethod
    def get_query_fields(self):
        return [{"title": "量纲名称：", "dataIndex": "dimension_name", "type": "CharField"},
                {"title": "量纲编码：", "dataIndex": "sei_id", "type": "CharField"},
                {"title": "量纲组成：", "dataIndex": "basic_dimension_composition", "type": "CharField"}]


class DimensionListSerializer(serializers.ModelSerializer):
    dimension_name = serializers.SerializerMethodField()
    basic_dimension_composition = serializers.SerializerMethodField()

    class Meta:
        model = Dimension
        fields = ["uuid", "dimension_name", "sei_id", "basic_dimension_composition",
                  "dimension_description", "dimension_comment"]

    def get_dimension_name(self, obj):
        return obj.show_full_name()
    
    def get_basic_dimension_composition(self, obj):
        basic_dimension_composition_content = ""
        for dimension_map in obj.dimensionmap_set.all():
            tmp = "{}({}) : {}".format(
                dimension_map.basic_dimension.show_short_name(), dimension_map.basic_dimension.basic_dimension_symbol, dimension_map.power)
            basic_dimension_composition_content += tmp + "\n"
        return basic_dimension_composition_content

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "量纲名称", "dataIndex": "dimension_name", "type": "CharField"},
            {"title": "量纲组成", "dataIndex": "basic_dimension_composition", "type": "TextField"}]


class DimensionCreateSerializer(serializers.ModelSerializer):
    basic_dimension_composition = serializers.JSONField()

    class Meta:
        model = Dimension
        fields = ["dimension_name", "dimension_name_en", "sei_id", "basic_dimension_composition",
                  "dimension_description", "dimension_description_en", "dimension_comment"]

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data
        
        
    
    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "量纲组成", "dataIndex": "basic_dimension_composition", "type": "TextField"}]
    

class DimensionModifyInfoSerializer(serializers.ModelSerializer):
    basic_dimension_composition = serializers.SerializerMethodField()

    class Meta:
        model = Dimension
        fields = ["dimension_name", "dimension_name_en", "sei_id", "basic_dimension_composition",
                  "dimension_description", "dimension_description_en", "dimension_comment"]

    def get_basic_dimension_composition(self, obj):
        basic_dimension_composition_content = {}
        for dimension_map in obj.dimensionmap_set.all():
            basic_dimension_composition_content[str(
                dimension_map.basic_dimension.uuid)] = dimension_map.power
        return basic_dimension_composition_content

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "量纲组成", "dataIndex": "basic_dimension_composition", "type": "TextField"}]


class DimensionModifyInfoInSerializer(serializers.ModelSerializer):
    basic_dimension_composition = serializers.JSONField()

    class Meta:
        model = Dimension
        fields = ["dimension_name", "dimension_name_en", "sei_id", "basic_dimension_composition",
                  "dimension_description", "dimension_description_en", "dimension_comment"]

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data
    
    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "量纲组成", "dataIndex": "basic_dimension_composition", "type": "TextField"}]


class DimensionInfoSerializer(serializers.ModelSerializer):
    basic_dimension_composition = serializers.SerializerMethodField()
    create_person = serializers.SerializerMethodField()
    modify_person = serializers.SerializerMethodField()

    class Meta:
        model = Dimension
        fields = ["dimension_name", "dimension_name_en", "sei_id", "basic_dimension_composition", "dimension_description", "dimension_description_en",
                  "dimension_comment", "create_person", "create_date", "modify_person", "modify_date"]

    def get_basic_dimension_composition(self, obj):
        basic_dimension_composition_content = ""
        for dimension_map in obj.dimensionmap_set.all():
            tmp = "{}({}) : {}".format(
                dimension_map.basic_dimension.show_short_name(), dimension_map.basic_dimension.basic_dimension_symbol, dimension_map.power)
            basic_dimension_composition_content += tmp + "\n"
        return basic_dimension_composition_content

    def get_create_person(self, obj):
        return obj.create_person.user_name

    def get_modify_person(self, obj):
        return obj.modify_person.user_name

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "量纲组成", "dataIndex": "basic_dimension_composition", "type": "TextField"}]
